package com.gjzhao.fmmall.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * @Description: 使用redis做限流，配置存放到redis的key
 * @Author: gjzhao
 * @Date Created in 2022-02-16 8:52 下午
 */
@Configuration
public class GatewayRedisKeyConfig {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Bean
    public KeyResolver getKeyResolver() {
        logger.info("-----进入获取key值");

        //拦截用户请求，使用请求路径中的path部分作为key
        // Mono.just 可以将string字符串构造为一个Mono对象
        return exchange -> Mono.just(exchange.getRequest().getURI().getPath());

        //也可在请求时，携带参数，其值作为key
        //return exchange -> Mono.just(exchange.getRequest().getQueryParams().get("user"));

        //todo 还可以基于ip进行限流
        // return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}
